﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Threading;
using HiTeachers.Utilities;

namespace HiTeachers.Web.SchedulerJobs
{
    public class Scheduler
    {
        private readonly string _heartbeatUrl = ConfigurationManager.AppSettings["SiteUrl"];
        private readonly int _sleepInterval = 1000 * 60 * 2; // 2 minutes
        private readonly IEnumerable<ISchedulerJob> _jobs = new List<ISchedulerJob>();

        public Scheduler() { }
        public Scheduler(string heartbeatUrl, int sleepInterval, IEnumerable<ISchedulerJob> jobs)
        {
            this._heartbeatUrl = heartbeatUrl;
            this._sleepInterval = 1000 * 60 * sleepInterval; //sleepInterval;
            this._jobs = jobs;
        }

        ~Scheduler()
        {
            Logger.Info("Scheduler stops at " + DateTime.Now.ToString());
        }

        public void Start()
        {
            while (true)
            {
                Logger.Info("Scheduler starts at " + DateTime.Now.ToString());

                try
                {
                    foreach (ISchedulerJob job in _jobs)
                    {
                        job.Execute();
                    }
                }
                catch (Exception e)
                {
                    // we log the exception and consume it, so that the thread can run forever
                    Logger.Error(e);
                }
                finally
                {
                    // to keep the application always running
                    try
                    {
                        var wc = new WebClient();
                        wc.DownloadString(_heartbeatUrl);
                    }
                    catch { }

                    Thread.Sleep(_sleepInterval);
                }
            }
        }
    }
}
